<script setup lang="ts">
// ----------------------- 导入相关依赖 -----------------------
import {nextTick, onMounted, onUnmounted, reactive, ref} from "vue";
import {ElMessage, FormInstance} from "element-plus";
import SysDialog from "@/components/dialog/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import useInstance from "@/hooks/useInstance";
import {Color, ColorListParam} from "@/api/color/type";
import {addApi, editApi, deleteApi, getListApi} from "@/api/color";
import {Search, Refresh, Plus, Edit, Delete, Document, InfoFilled, Setting, Switch, Brush} from '@element-plus/icons-vue'

// ----------------------- 组件状态定义 -----------------------
const {dialog, onShow, onClose} = useDialog()
const {global} = useInstance()

// 表格高度自适应
const tableHeight = ref(0)

// ----------------------- 表格相关 -----------------------
const tableData = ref([])
const loading = ref(false)
const paginationData = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
})

// ----------------------- 查询表单相关 -----------------------
const searchForm = reactive<ColorListParam>({
  colorCode: undefined,
  colorName: undefined,
  isActive: undefined,
  page: 1,
  limit: 10
})

// 查询方法
const search = () => {
  paginationData.currentPage = 1
  getTableData()
}

// 重置查询
const reset = () => {
  searchForm.colorCode = undefined
  searchForm.colorName = undefined
  searchForm.isActive = undefined
  search()
}

// ----------------------- 表格数据处理 -----------------------
const getTableData = async () => {
  loading.value = true
  try {
    searchForm.page = paginationData.currentPage
    searchForm.limit = paginationData.pageSize
    let res = await getListApi(searchForm)
    if (res && res.data) {
      tableData.value = res.data.list
      paginationData.total = res.data.total
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
  } finally {
    loading.value = false
  }
}

// ----------------------- 新增/编辑表单相关 -----------------------
const addFormRef = ref<FormInstance>()
const addForm = reactive<Color>({
  id: undefined,
  colorCode: undefined,
  colorName: undefined,
  description: undefined,
  isActive: 0
})

// 表单校验规则
const rules = {
  colorCode: [{required: true, message: '请输入颜色编码', trigger: 'blur'}],
  colorName: [{required: true, message: '请输入颜色名称', trigger: 'blur'}]
}

// 打开新增弹框
const openAdd = () => {
  dialog.title = '新增颜色'
  dialog.width = 600
  dialog.height = 300
  onShow()
}

// 打开编辑弹框
const openEdit = (row: Color) => {
  dialog.title = '编辑颜色'
  dialog.width = 600
  dialog.height = 300
  nextTick(() => {
    Object.assign(addForm, row)
  })
  onShow()
}

// 关闭弹框
const closeDialog = () => {
  addFormRef.value?.resetFields()
  Object.assign(addForm, {
    id: undefined,
    colorCode: undefined,
    colorName: undefined,
    description: undefined,
    isActive: 0
  })
  onClose()
}

// 提交表单
const submit = async () => {
  await addFormRef.value?.validate()
  try {
    if (addForm.id) {
      await editApi(addForm)
      ElMessage.success('编辑成功')
    } else {
      await addApi(addForm)
      ElMessage.success('新增成功')
    }
    getTableData()
    closeDialog()
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// ----------------------- 删除相关 -----------------------
const deleteOne = async (id: number) => {
  const confirm = await global.$myConfirm('确定要删除该颜色吗？')
  if (confirm) {
    try {
      await deleteApi(id)
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && paginationData.currentPage > 1) {
        paginationData.currentPage--
      }
      getTableData()
    } catch (error) {
      console.error('删除失败:', error)
    }
  }
}

// ----------------------- 生命周期钩子 -----------------------
onMounted(() => {
  getTableData()
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
})

// 监听窗口大小变化
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <el-main class="color-main">
    <div class="main-container">
      <!-- 查询表单区域 -->
      <el-card class="search-card" shadow="hover">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="颜色编码">
            <el-input 
              v-model="searchForm.colorCode" 
              placeholder="请输入颜色编码" 
              clearable
              prefix-icon="Document"
            />
          </el-form-item>
          <el-form-item label="颜色名称">
            <el-input 
              v-model="searchForm.colorName" 
              placeholder="请输入颜色名称" 
              clearable
              prefix-icon="Brush"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select 
              v-model="searchForm.isActive" 
              placeholder="是否启用" 
              clearable 
              class="status-select"
            >
              <el-option label="启用" :value="0"/>
              <el-option label="禁用" :value="1"/>
            </el-select>
          </el-form-item>
          <el-form-item class="search-buttons">
            <el-button type="primary" @click="search" class="search-btn" :icon="Search">
              查询
            </el-button>
            <el-button @click="reset" class="reset-btn" :icon="Refresh">
              重置
            </el-button>
            <el-button type="success" @click="openAdd" class="add-btn" :icon="Plus">
              新增
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 表格区域 -->
      <el-card class="table-card" shadow="hover">
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          :height="tableHeight"
          class="data-table"
          highlight-current-row
        >
          <el-table-column type="index" label="序号" width="70" align="center"/>
          <el-table-column prop="colorCode" label="颜色编码" min-width="120" align="center"/>
          <el-table-column prop="colorName" label="颜色名称" min-width="120" align="center"/>
          <el-table-column prop="description" label="颜色描述" min-width="200" align="center" show-overflow-tooltip/>
          <el-table-column prop="isActive" label="状态" min-width="80" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.isActive === 0 ? 'success' : 'danger'" effect="light">
                {{ scope.row.isActive === 0 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" fixed="right" align="center">
            <template #default="scope">
              <div class="action-buttons">
                <el-button type="primary" size="small" @click="openEdit(scope.row)" class="edit-btn" :icon="Edit">
                  编辑
                </el-button>
                <el-button type="danger" size="small" @click="deleteOne(scope.row.id)" class="delete-btn" :icon="Delete">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-model:current-page="paginationData.currentPage"
          v-model:page-size="paginationData.pageSize"
          :page-sizes="[10, 20, 50]"
          :total="paginationData.total"
          layout="total, sizes, prev, pager, next, jumper"
          class="pagination"
          @size-change="getTableData"
          @current-change="getTableData"
        />
      </el-card>
    </div>

    <!-- 新增/编辑弹框 -->
    <sys-dialog
      :title="dialog.title"
      :width="dialog.width"
      :visible="dialog.visible"
      :height="dialog.height"
      @onClose="closeDialog"
      @onConfirm="submit"
      custom-class="color-dialog"
    >
      <template #content>
        <el-form
          ref="addFormRef"
          :model="addForm"
          :rules="rules"
          label-width="90px"
          class="color-form"
        >
          <el-card class="form-card" shadow="never">
            <template #header>
              <div class="form-header">
                <el-icon><Document /></el-icon>
                <span>基本信息</span>
              </div>
            </template>
            <el-form-item label="颜色编码" prop="colorCode">
              <el-input v-model="addForm.colorCode" placeholder="请输入颜色编码"/>
            </el-form-item>
            <el-form-item label="颜色名称" prop="colorName">
              <el-input v-model="addForm.colorName" placeholder="请输入颜色名称"/>
            </el-form-item>
          </el-card>
          
          <el-card class="form-card" shadow="never">
            <template #header>
              <div class="form-header">
                <el-icon><InfoFilled /></el-icon>
                <span>详细信息</span>
              </div>
            </template>
            <el-form-item label="颜色描述">
              <el-input
                v-model="addForm.description"
                type="textarea"
                :rows="3"
                placeholder="请输入颜色描述"
              />
            </el-form-item>
          </el-card>
          
          <el-card class="form-card" shadow="never">
            <template #header>
              <div class="form-header">
                <el-icon><Switch /></el-icon>
                <span>状态设置</span>
              </div>
            </template>
            <el-form-item label="状态">
              <el-radio-group v-model="addForm.isActive" class="status-radio">
                <el-radio :label="0">启用</el-radio>
                <el-radio :label="1">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-card>
        </el-form>
      </template>
    </sys-dialog>
  </el-main>
</template>

<style scoped lang="scss">
.color-main {
  padding: 0;
}

.main-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;
  
  :deep(.el-card__body) {
    padding: 15px 20px;
  }
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  
  .el-form-item {
    margin-bottom: 0;
    margin-right: 16px;
  }
  
  .status-select {
    width: 120px;
  }
  
  .search-buttons {
    margin-left: auto;
    
    .el-button {
      margin-left: 8px;
      transition: all 0.3s;
      
      &:first-child {
        margin-left: 0;
      }
    }
    
    .search-btn {
      background: linear-gradient(135deg, #1989fa, #0056b3);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
      }
    }
    
    .add-btn {
      background: linear-gradient(135deg, #67c23a, #409eff);
      border: none;
      
      &:hover {
        opacity: 0.9;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
      }
    }
    
    .reset-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(144, 147, 153, 0.2);
    }
  }
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: calc(100vh - 180px);
  margin-bottom: 0;
  
  :deep(.el-card__body) {
    padding: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.data-table {
  border-radius: 4px;
  flex: 1;
  
  :deep(.el-table__header-wrapper) {
    th {
      background-color: #f2f6fc;
      font-weight: 600;
    }
  }
  
  :deep(.el-table__row) {
    &:hover {
      td {
        background-color: #ecf5ff;
      }
    }
  }
  
  .action-buttons {
    display: flex;
    justify-content: center;
    
    .el-button {
      padding: 6px 10px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
      }
    }
    
    .edit-btn {
      margin-right: 10px;
    }
  }
}

.pagination {
  padding: 15px 20px;
  justify-content: flex-end;
  background: #fff;
  border-radius: 0 0 8px 8px;
}

.color-form {
  padding: 20px;

  .form-card {
    margin-bottom: 15px;
    border-radius: 8px;
    transition: all 0.3s;
    overflow: hidden;
    border: 1px solid #ebeef5;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    :deep(.el-card__header) {
      padding: 10px 15px;
      background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
      border-bottom: 1px solid #e1f3d8;
    }
    
    .form-header {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
      display: flex;
      align-items: center;
      gap: 8px;
      
      .el-icon {
        color: #67c23a;
      }
    }
  }
  
  :deep(.el-input__wrapper), :deep(.el-textarea__inner) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    
    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }
    
    &.is-focus {
      box-shadow: 0 0 0 1px #67c23a inset;
    }
  }
  
  :deep(.el-form-item__label) {
    font-weight: 500;
  }
  
  .status-radio {
    :deep(.el-radio__input.is-checked .el-radio__inner) {
      background-color: #67c23a;
      border-color: #67c23a;
    }
    
    :deep(.el-radio__label) {
      color: #606266;
    }
    
    :deep(.el-radio__input.is-checked + .el-radio__label) {
      color: #67c23a;
    }
  }
}

:deep(.color-dialog) {
  border-radius: 8px;
  overflow: hidden;
  
  .el-dialog__header {
    padding: 15px 20px;
    margin: 0;
    background: linear-gradient(90deg, #f0f9eb, #e1f3d8);
    border-bottom: 1px solid #e1f3d8;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #67c23a;
    }
    
    .el-dialog__headerbtn {
      top: 15px;
    }
  }
  
  .el-dialog__body {
    padding: 0;
  }
  
  .el-dialog__footer {
    padding: 10px 20px;
    border-top: 1px solid #ebeef5;
    background-color: #f5f7fa;
    
    .el-button {
      padding: 8px 20px;
      border-radius: 4px;
      transition: all 0.3s;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }
}
</style>
